/*-+-*****************************************************************************
 Copyright (C) 2009-2012 Oceanside Software Corporation (R)
 Dallas, Texas

 Author       : Jason T. Brower
 Purpose      : This file is part of a point-of-sale software package
                originally written for Table-Service Restaurants.
              
 Date         : July 8th of 2012
              
 History      : The application that this software file belongs to was 
                written over a 3-Year period.  The first version was written
                in C# .Net 3.5 using Windows Forms.  Being new to .Net at
                the time, I soon learned of Windows Presentation Foundation,
                liked the graphics capabilities and databinding so I
                migrated to WPF.  When the .Net 4.0 framework was released
                the application was migrated from 3.5 to 4.0. Now today,
                .Net 4.5 RC is out and I was already in process of migrating
                before I made this public.
                
Excuse Me     : Please excuse the coding style, it is not representative of
                my typical work.  During the three years I was under a very
                tight budget, constantly running out of funding and was 
                working 18 hour days hyped up on 5-Hour Energy.  The 
                design is not textbook.  It is monolythic because of
                previous issues I will not get into.  There are few comments
                in the code and the ones that are there may be incorrect.
                
What it is not: This is not the exact version that I took through PA-DSS 2.0
                nor is it the exact version running at my customer sites.
                I removed some details for security purposes including some
                encryption algorithms.  The reporting was removed because
                I was including a third party library that cannot be 
                published with this Open Source.
                
What it is    : This application has been running at high volume restaraunts
                for over a year.  It never freezes, crashes or does anything
                unexpected.  So long as it is built, installed and configured
                correctly, it is a strong system that we can all enhance.

Contact       : Please note that I can no longer work for free.  However, you
                can reach me at information@oceansidesw.com.                                                      

*********************************************************************************/
using System;
using System.Threading.Tasks;
using System.Linq;
using Oceanside.Payments.Credit;
using Oceanside.Payments;
#if _LOCALDB
  using Oceanside.LocalDB;
#else
using Oceanside.RemoteDB;
#endif
namespace Oceanside
{
    class HandleVoidSale : BindInterface
    {
        public HandleVoidSale(string name = "")
        {
            Text = name;
        }

        override public System.Windows.Visibility IsVisible
        {
            get
            {
                if (CloseCheck.StateObject.SelectedTransactionNotNull &&
                    !CloseCheck.StateObject.SelectedTransactionIsAccount &&
                    !CloseCheck.StateObject.SelectedTransactionWasVoided &&
                    CloseCheck.StateObject.SelectedOrderNotNull &&
                    !CloseCheck.StateObject.SelectedOrderIsClosed &&
                    CloseCheck.StateObject.CurrentUserCanVoidPayment)
                {
                    return System.Windows.Visibility.Visible;
                }
                else
                {
                    return System.Windows.Visibility.Hidden;
                }
            }
        }

        override public void Clicked()
        {
            try
            {
                CloseCheckWindow.StopChangeDueBlink();

                if (CCBindings.SelectedTransaction != null)
                {
                    if (CCBindings.SelectedTransaction.TransactionType == TRANSACTION.CONST_PAY_CREDIT)
                    {
                        TRANSACTION_RESPONSE tr = SHIFT.GlobalContext.TRANSACTION_RESPONSES.
                            Where(t => t.Id == CCBindings.SelectedTransaction.TransactionTypeId).FirstOrDefault();

                        if (tr.TranCode.Equals("PreAuth"))
                        {
                            SHIFT.SelectedOrder.TRANSACTIONS.Remove(CCBindings.SelectedTransaction);
                            SHIFT.GlobalContext.TRANSACTIONS.DeleteObject(CCBindings.SelectedTransaction);
                            CCBindings.RefreshThreadSafe(true);
                        }
                        else if (tr.TranCode.Equals("PreAuthCapture") || tr.TranCode.Equals("Adjust"))
                        {
                            PerformVoidOnCapture();
                            CCBindings.RefreshThreadSafe(false);
                        }
                    }
                    else if (CCBindings.SelectedTransaction.TransactionType == TRANSACTION.CONST_PAY_GIFT)
                    {
                        PerformVoidOnPrepaidSale();
                        CCBindings.RefreshThreadSafe(false);
                    }
                    else
                    {
                        SHIFT.SelectedOrder.TRANSACTIONS.Remove(CCBindings.SelectedTransaction);
                        SHIFT.GlobalContext.TRANSACTIONS.DeleteObject(CCBindings.SelectedTransaction);
                        CCBindings.RefreshThreadSafe(true);
                    }
                    SHIFT.GlobalContext.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                Constants.ErrorDispatcher.Notify(Error.EType.E_PLACEHOLDER, ex);
            }
        }

        private static void PerformVoidOnPrepaidSale()
        {
            MagneticCard magCard = null;

            CACHE cache = SHIFT.GlobalContext.CACHES.Where(c => c.Id == CCBindings.SelectedTransaction.ExtId).FirstOrDefault();

            ///I HAVE REMOVED THE ENCRPTION ALGORITHM TO PROTECT MY EXISTING CUSTOMERS FROM HACKS FROM MAKING THIS PUBLIC
            ///KNOWLEDGE.  YOU MUST USE A STRONG ENCRYPTION ALGORITHM HERE AND NEVER STORE THE FULL MAG STRIPE EVER, NEVER.
            string pan = "1111111111111111";
            string expire = "1111";
            //string pan = Crpt.ToString(cache.BinP);
            //string expr = Crpt.ToString(cache.BinE);
            magCard = new MagneticCard(pan, expire);

            Payments.Prepaid.VoidSale data = new Payments.Prepaid.VoidSale();

            TRANSACTION_RESPONSE originalResponse = SHIFT.GlobalContext.TRANSACTION_RESPONSES.
                Where(r => r.Id == CCBindings.SelectedTransaction.TransactionTypeId).FirstOrDefault();

            data.InvoiceNo = originalResponse.Id.ToString();
            data.RefNo = originalResponse.RefNo;
            data.AuthCode = originalResponse.AuthCode;
            data.Purchase = originalResponse.Authorize;
            data.IpPort = "9100";
            string response = data.Request(magCard);

            TRANSACTION_RESPONSE respMessage = new TRANSACTION_RESPONSE();
            respMessage.Parse(response);

            if (respMessage.CmdStatusOk)
            {
                originalResponse.Parse(response);
                CCBindings.SelectedTransaction.WasVoided = true;
                SHIFT.GlobalContext.SaveChanges();
            }
            else
            {
                UMD.ShowGuiMessageSTASafe_NOTHROW("The processor returned an error code of ["
                    + respMessage.CmdStatus + "] and a message of [" + respMessage.TextResponse + "].");
            }
        }

        private static void PerformVoidOnCapture()
        {
            MagneticCard magCard = null;

            CACHE cache = SHIFT.GlobalContext.CACHES.Where(c => c.Id == CCBindings.SelectedTransaction.ExtId).FirstOrDefault();
            ///I HAVE REMOVED THE ENCRPTION ALGORITHM TO PROTECT MY EXISTING CUSTOMERS FROM HACKS FROM MAKING THIS PUBLIC
            ///KNOWLEDGE.  YOU MUST USE A STRONG ENCRYPTION ALGORITHM HERE AND NEVER STORE THE FULL MAG STRIPE EVER, NEVER.
            //string pan = Crpt.ToString(cache.BinP);
            //string expire = Crpt.ToString(cache.BinE);
            string pan = "1111111111111111";
            string exp = "1111";
            magCard = new MagneticCard(pan, exp);

            VoidSale data = new VoidSale();

            TRANSACTION_RESPONSE originalResponse = SHIFT.GlobalContext.TRANSACTION_RESPONSES.
                Where(r => r.Id == CCBindings.SelectedTransaction.TransactionTypeId).FirstOrDefault();

            data.InvoiceNo = originalResponse.Id.ToString();
            data.RefNo = originalResponse.RefNo;
            data.AuthCode = originalResponse.AuthCode;

            data.ProcessData = originalResponse.ProcessData;  ///For Mercury Real-Time Reversal Support of Prepaid.
            data.AcqRefData = originalResponse.AcqRefData;    ///For Mercury Real-Time Reversal Support of Prepaid.
            data.Purchase = originalResponse.Authorize;

            string response = data.Request(magCard);

            TRANSACTION_RESPONSE respMessage = new TRANSACTION_RESPONSE();
            respMessage.Parse(response);

            if (respMessage.CmdStatusOk)
            {
                originalResponse.Parse(response);
                CCBindings.SelectedTransaction.WasVoided = true;
                SHIFT.GlobalContext.SaveChanges();
            }
            else
            {
                UMD.ShowGuiMessageSTASafe_NOTHROW("The processor returned an error code of ["
                    + respMessage.CmdStatus + "] and a message of [" + respMessage.TextResponse + "].");
            }
        }
    }
}
